package com.itchu.auth.config;


import com.itchu.auth.filter.TokenVerifyFilter;
import com.itchu.auth.handler.*;
import com.itchu.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserService sysUserService;     // 自定义userDetail继承接口的实现类
    @Autowired
    private JwtProperties prop;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private CustomizeAuthenticationEntryPoint authenticationEntryPoint;    // 未登录用户访问时返回的异常处理
    @Autowired
    CustomizeAuthenticationFailureHandler failureHandler;    // 用户名或密码错误等异常处理
    @Autowired
    CustomizeAuthenticationSuccessHandler successHandler;    // 认证成功的处理
    @Autowired
    CustomizeAccessDeniedHandler accessDeniedHandler;   //权限不足的异常处理
    @Autowired
    CustomizeLogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    CustomizeAccessDecisionManager accessDecisionManager;
    @Autowired
    CustomizeAbstractSecurityInterceptor securityInterceptor;
    @Autowired
    CustomizeFilterInvocationSecurityMetadataSource metadataSource;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(sysUserService)
                .passwordEncoder(passwordEncoder);
    }

    public void configure(HttpSecurity http) throws Exception {
        http
                // 关闭跨站请求防护
                .cors().and().csrf().disable()
                .authorizeRequests()

                // 允许通过的路径
                .antMatchers("/song/**","/singer/**").permitAll()

                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(accessDecisionManager);
                        object.setSecurityMetadataSource(metadataSource);
                        return object;
                    }
                })
                // 登录进去
                .and().formLogin()
                .permitAll()
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                // 用户未登录访问时的异常(权限拒绝，登录失效等)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint)
                //登出
                .and().logout().permitAll()//允许所有用户
                .logoutSuccessHandler(logoutSuccessHandler).//登出成功处理逻辑
                deleteCookies("JSESSIONID")//登出之后删除cookie
                // 过滤器
                .and()
//                .addFilter(new TokenLonginFilter(authenticationManager(), prop))
                .addFilter(new TokenVerifyFilter(authenticationManager(), prop,redisTemplate))


                // 禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(securityInterceptor, FilterSecurityInterceptor.class);
    }
}
